package com.bootdo.hjh.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Queue;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.bootdo.common.annotation.Log;
import com.bootdo.common.utils.MD5Utils;
import com.bootdo.common.utils.R;
import com.bootdo.hjh.cache.Group;
import com.bootdo.hjh.cache.GroupTree;
import com.bootdo.hjh.cache.MemberCache;
import com.bootdo.hjh.cache.Node;
import com.bootdo.hjh.cache.NodeInfo;
import com.bootdo.hjh.cache.NodeVO;
import com.bootdo.hjh.cache.ProductCache;
import com.bootdo.hjh.service.OrderService;
import com.bootdo.hjh.service.PointsService;
import com.bootdo.hjh.vo.GroupInfo;
import com.bootdo.shop.service.ShopOrderService;
import com.bootdo.system.dao.UserDao;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.service.UserService;

/**
 * Created by qingyong on 2018/4/14.
 */
@Controller
public class ToolController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ToolController.class);
    @Autowired
    MemberCache memberCache;

    @Autowired
    ProductCache productCache;

    @Autowired
    UserService userService;

    @Autowired
    UserDao userDao;

    @Autowired
    private OrderService orderService;

    @Autowired
    private PointsService pointsService;

    @Autowired
    private ShopOrderService shopOrderService;

    //@GetMapping("/tools")
    public String tools(){
        return "hjh/tools";
    }

    @GetMapping("/tool/memberCache/refresh")
    @ResponseBody
    public R reloadMemberCache(){
        memberCache.reloadCacheFromDb();
        return R.ok();
    }

    @GetMapping("/tool/productCache/refresh")
    @ResponseBody
    public R reloadProductCache(){
        productCache.reloadCacheFromDb();
        return R.ok();
    }

    @Log("手动触发跑批业务")
    @GetMapping("/trigger/tasks")
    @ResponseBody
    public R triggerTasks(){
    		LOGGER.info("=========== VIP分红   ============");
    		pointsService.vipBonus();
    		pointsService.agentBonus();
    		pointsService.agent2Bonus();
    		pointsService.agent3Bonus();
    		pointsService.agent4Bonus();
    		pointsService.agent5Bonus();
        return R.ok();
    }


    @Log("订单设置为已支付")
    //@GetMapping("/order/finish")
    @ResponseBody
    public R orderFinish(String no){
    		LOGGER.info("=========== 订单设置为已支付   ============");
    		orderService.updateOrderToPaid(no,"测试支付");
        return R.ok();
    }

    //@Log("测试商城订单分润")
    @GetMapping("/order/fenrun")
    @ResponseBody
    public R orderFenrun(String no){
    		LOGGER.info("=========== 测试商城订单分润   ============");
    		shopOrderService.paySuccessCallback(no,"支付宝支付", null, "abc");
        return R.ok();
    }

    @Log("清洗用户等级")
    @GetMapping("/user/updateLevel")
    @ResponseBody
    public R updateLevel(){
        LOGGER.info("=========== 清洗用户等级   ============");

//        user_id, level, recommend_user_id
        List<UserDO> userDOS = userDao.selectAllUserForLevel();

        // 找出根
        List<UserDO> rootUsers =
                userDOS.stream().filter(p -> p.getRecommendUserId() == null).collect(Collectors.toList());
        Map<Long, UserDO> idMap = new HashMap<>();
        Map<Long, List<UserDO>> recommandIdMap = new HashMap<>();
        for (UserDO userDO : userDOS) {
            idMap.put(userDO.getUserId(), userDO);
            if (userDO.getRecommendUserId()!=null) {
                if (recommandIdMap.get(userDO.getRecommendUserId()) == null) {
                    recommandIdMap.put(userDO.getRecommendUserId(), new ArrayList<>());
                }
                recommandIdMap.get(userDO.getRecommendUserId()).add(userDO);
            }
        }
        JSONArray jsonArray = new JSONArray();
        Queue<UserDO> queue = new LinkedList<>();
        int level = 0;
        for (UserDO rootUser : rootUsers) {
            if (rootUser.getLevel() != level) {
                jsonArray.add("update sys_user set level = " + level +" where user_id = " + rootUser.getUserId() + ";");
                rootUser.setLevel(level);
            }
            queue.offer(rootUser);
        }

        while (!queue.isEmpty()) {
            UserDO parent = queue.poll();
            level = parent.getLevel() + 1;
            List<UserDO> recommands = recommandIdMap.get(parent.getUserId());
            if (!CollectionUtils.isEmpty(recommands)) {
                for (UserDO recommand : recommands) {
                    if (recommand.getLevel() != level) {
                        jsonArray.add("update sys_user set level = " + level +" where user_id = " + recommand.getUserId() + ";");
                        recommand.setLevel(level);
                    }
                    queue.offer(recommand);
                }
            }
        }
        return new R(jsonArray);
    }




    public static void main(String[] args) {
		String payPwd = MD5Utils.encrypt("zc6268");
		System.out.println(payPwd);
	}
}
